<!--
 * Copyright (c) 2013-Now http://jeesite.com All rights reserved.
 * No deletion without permission, or be held responsible to law.
 * @author YDZ
-->
<template>
  <BasicDrawer
    v-bind="$attrs"
    :showFooter="true"
    :okAuth="'material:receive:pmMaterialneedArr:edit'"
    @register="registerDrawer"
    @ok="handleSubmit('1')"
    width="60%"
  >
    <template #title>
      <Icon :icon="getTitle.icon" class="pr-1 m-1" />
      <span> {{ getTitle.value }} </span>
    </template>
    <BasicForm @register="registerForm">
      <template #clSelect>
        <ListSelect
          selectType="materialSelect"
          :checkbox="true"
          :params="queryParams"
          :selectList="listSelectRef"
          @select="handSelect"
        />
      </template>
      <template #pmMaterialneedArrsList>
        <BasicTable
          @register="registerPmMaterialneedArrsTable"
          @row-click="handlePmMaterialneedArrsRowClick"
        />
        <!-- <a-button
          v-if="record.status != '0'"
          class="mt-2"
          @click="handlePmMaterialneedArrsAdd"
          v-auth="'material:receive:pmMaterialneedArr:edit'"
        >
          <Icon icon="ant-design:plus-circle-outlined" /> {{ t('新增') }}
        </a-button> -->
      </template>
    </BasicForm>
    <template #centerFooter>
      <!-- <a-popconfirm
        title="是否确认拒收？"
        ok-text="是"
        cancel-text="否"
        placement="bottom"
        @confirm="handleSubmit('3')"
      >
        <a-button
          class="mt-2"
          type="error"
          v-auth="'material:receive:pmMaterialneedArr:edit'"
          @click="handleReject()"
        >
          <Icon icon="ant-design:check-outlined" /> {{ t('拒 收') }}
        </a-button>
      </a-popconfirm> -->
      <a-button
        class="mt-2"
        type="error"
        v-auth="'material:receive:pmMaterialneedArr:edit'"
        @click="handleReject()"
      >
        <Icon icon="ant-design:check-outlined" /> {{ t('拒 收') }}
      </a-button>
    </template>
  </BasicDrawer>
  <!-- 拒收原因 -->
  <BasicModal v-bind="$attrs" @register="registerModal" title="拒收原因" @ok="handleSubmit('3')">
    <BasicForm @register="registerReasonForm" />
  </BasicModal>
</template>
<script lang="ts">
  export default defineComponent({
    name: 'ViewsMaterialReceivePmMaterialneedArrForm',
  });
</script>
<script lang="ts" setup>
  import { defineComponent, ref, computed, reactive } from 'vue';
  import { useI18n } from '/@/hooks/web/useI18n';
  import { useMessage } from '/@/hooks/web/useMessage';
  import { router } from '/@/router';
  import { Icon } from '/@/components/Icon';
  import { BasicForm, FormSchema, useForm } from '/@/components/Form';
  import { BasicTable, useTable } from '/@/components/Table';
  import { BasicDrawer, useDrawerInner } from '/@/components/Drawer';
  // import {
  //   PmMaterialneedArr,
  //   pmMaterialneedArrSave,
  //   pmMaterialneedArrForm,
  // } from '/@/api/material/receive/pmMaterialneedArr';
  import { BasicModal, useModal } from '/@/components/Modal';
  import {
    SrmAsn,
    pmAsnShrecAsnform,
    pmAsnShrecSaveByAsn,
  } from '/@/api/material/receive/pmAsnShrec';

  import { ListSelect } from '/@/components/ListSelect';

  const emit = defineEmits(['success', 'register']);

  const { t } = useI18n('material.receive.pmMaterialneedArr');
  const { showMessage } = useMessage();
  const record = ref<PmMaterialneedArr>({} as PmMaterialneedArr);
  const getTitle = computed(() => ({
    icon: router.currentRoute.value.meta.icon || 'ant-design:book-outlined',
    // value: record.value.isNewRecord ? t('新增材料收货') : t('编辑材料收货'),
    value: t('确定收货'),
  }));

  let queryParams = ref({});
  let listSelectRef = ref([]);

  const inputFormSchemas: FormSchema[] = [
    {
      label: t('工程编号'),
      field: 'projectno',
      component: 'Input',
      dynamicDisabled: true,
      componentProps: {
        maxlength: 100,
      },
      // required: true,
    },
    {
      label: t('工程名称'),
      field: 'projectname',
      component: 'Input',
      dynamicDisabled: true,
      componentProps: {
        maxlength: 200,
      },
    },
    {
      label: t('供货单号'),
      field: 'djno',
      component: 'Input',
      dynamicDisabled: true,
      componentProps: {
        maxlength: 100,
      },
    },
    {
      label: t('供货日期'),
      field: 'ddate',
      component: 'DatePicker',
      dynamicDisabled: true,
      componentProps: {
        format: 'YYYY-MM-DD',
        // showTime: { format: 'HH:mm' },
      },
    },
    {
      label: t('供应商'),
      field: 'venName',
      component: 'Input',
      dynamicDisabled: true,
      componentProps: {
        maxlength: 100,
      },
    },
    {
      label: t('备注信息'),
      field: 'remarks',
      component: 'InputTextArea',
      componentProps: {
        maxlength: 500,
      },
      colProps: { lg: 24, md: 24 },
    },
    {
      label: t('图片上传'),
      field: 'dataMap',
      component: 'Upload',
      componentProps: {
        loadTime: computed(() => record.value.__t),
        bizKey: computed(() => record.value.id),
        bizType: 'pmAsnShrec_image',
        uploadType: 'image',
        isPreview: true,
      },
      colProps: { lg: 24, md: 24 },
      // 文件上传的必填验证实例
      rules: [
        { required: true },
        {
          validator(_rule, value) {
            return new Promise((resolve, reject) => {
              const len = !value || value['pmAsnShrec_image__len'] || 0;
              if (len == 0) reject(t('请上传图片'));
              else resolve();
            });
          },
        },
      ],
    },
    // {
    //   label: t('到货单'),
    //   field: 'dataMap',
    //   component: 'Upload',
    //   componentProps: {
    //     loadTime: computed(() => record.value.__t),
    //     bizKey: computed(() => record.value.id),
    //     bizType: 'PmMaterialneedArrAsn_image',
    //     uploadType: 'image',
    //     isPreview: true,
    //   },
    //   colProps: { lg: 24, md: 24 },
    // },
    {
      label: t(''),
      field: 'pmMaterialneedArrsList',
      component: 'Input',
      colProps: { lg: 24, md: 24 },
      slot: 'pmMaterialneedArrsList',
    },
  ];

  const [registerForm, { resetFields, setFieldsValue, validate }] = useForm({
    labelWidth: 120,
    schemas: inputFormSchemas,
    baseColProps: { lg: 12, md: 24 },
  });

  const inputReasonFormSchemas: FormSchema[] = [
    {
      label: t('拒收原因'),
      field: 'remarks',
      component: 'InputTextArea',
      componentProps: {
        maxlength: -1,
        rows: 5,
        placeholder: t('请输入拒收原因'),
      },
      colProps: { lg: 24, md: 24 },
    },
  ];

  const [
    registerReasonForm,
    {
      resetFields: resetReasonFields,
      setFieldsValue: setReasonFieldsValue,
      validate: validateReason,
    },
  ] = useForm({
    labelWidth: 120,
    schemas: inputReasonFormSchemas,
    baseColProps: { lg: 24, md: 24 },
  });

  const [registerModal, { openModal, closeModal }] = useModal();
  const [registerPmMaterialneedArrsTable, pmMaterialneedArrsTable] = useTable({
    // actionColumn: {
    //   width: 60,
    //   actions: (record1: Recordable) => [
    //     {
    //       icon: 'ant-design:delete-outlined',
    //       color: 'error',
    //       popConfirm: {
    //         title: '是否确认删除',
    //         confirm: handlePmMaterialneedArrsDelete.bind(this, record1),
    //       },
    //       auth: 'material:receive:pmMaterialneedArr:edit',
    //       ifShow: () => record.value.status != '0',
    //     },
    //   ],
    // },
    rowKey: 'id',
    pagination: false,
    bordered: true,
    size: 'small',
    inset: true,
  });

  async function setPmMaterialneedArrsTableData(_res: Recordable) {
    pmMaterialneedArrsTable.setColumns([
      {
        title: t('订单号'),
        dataIndex: 'cpoid',
        width: 150,
        align: 'left',
      },
      {
        title: t('材料编码'),
        dataIndex: 'basInv.mcode',
        width: 110,
        align: 'left',
      },
      {
        title: t('材料名称'),
        dataIndex: 'basInv.mname',
        width: 200,
        align: 'left',
      },
      {
        title: t('规格型号'),
        dataIndex: 'basInv.mstd',
        width: 150,
        align: 'left',
      },
      {
        title: t('单位'),
        dataIndex: 'basInv.unit',
        width: 60,
        align: 'left',
      },
      {
        title: t('数量'),
        dataIndex: 'iqty',
        width: 80,
        align: 'right',
        fixed: 'right',
      },
      {
        title: t('备注'),
        dataIndex: 'remarks',
        width: 150,
        align: 'left',
      },

      // {
      //   title: t('来源ID'),
      //   dataIndex: 'sourceId',
      //   width: 130,
      //   align: 'left',
      //   editRow: true,
      //   editComponent: 'Input',
      //   editComponentProps: {
      //     maxlength: 64,
      //   },
      //   editRule: true,
      // },
    ]);
    pmMaterialneedArrsTable.setTableData(record.value.childList || []);
  }

  function handlePmMaterialneedArrsRowClick(record: Recordable) {
    record.onEdit?.(true, false);
  }

  function handlePmMaterialneedArrsAdd() {
    listSelectRef.value = [];
    document.getElementById('form_item_clid1')?.click();
    // pmMaterialneedArrsTable.insertTableDataRecord({
    //   id: new Date().getTime(),
    //   isNewRecord: true,
    //   editable: true,
    // });
  }

  function handlePmMaterialneedArrsDelete(record: Recordable) {
    pmMaterialneedArrsTable.deleteTableDataRecord(record);
  }

  async function getPmMaterialneedArrsList() {
    let pmMaterialneedArrsListValid = true;
    let pmMaterialneedArrsList: Recordable[] = [];
    for (const record of pmMaterialneedArrsTable.getDataSource()) {
      if (!(await record.onEdit?.(false, true))) {
        pmMaterialneedArrsListValid = false;
      }
      pmMaterialneedArrsList.push({
        ...record,
        id: !!record.isNewRecord ? '' : record.id,
      });
    }
    for (const record of pmMaterialneedArrsTable.getDelDataSource()) {
      if (!!record.isNewRecord) continue;
      pmMaterialneedArrsList.push({
        ...record,
        status: '1',
      });
    }
    if (!pmMaterialneedArrsListValid) {
      throw { errorFields: [{ name: ['pmMaterialneedArrsList'] }] };
    }
    return pmMaterialneedArrsList;
  }

  const [registerDrawer, { setDrawerProps, closeDrawer }] = useDrawerInner(async (data) => {
    setDrawerProps({ loading: true });
    await resetFields();
    const res = await pmAsnShrecAsnform({ id: data.id });
    record.value = (res.srmAsn || {}) as SrmAsn;
    record.value = { ...data, ...record.value };
    // if (!data.id) {
    //   record.value = { ...record.value, ...data };
    // }
    record.value.__t = new Date().getTime();
    // setDrawerProps({ showOkBtn: record.value.status == '0' ? false : true });
    // queryParams.value = {
    //   pcode: record.value.projectno,
    // };
    setFieldsValue(record.value);
    setPmMaterialneedArrsTableData(res);
    setDrawerProps({ loading: false });
  });

  // 拒收原因
  function handleReject() {
    setReasonFieldsValue({ remarks: '' });
    openModal(true, {});
  }

  async function handleSubmit(status) {
    try {
      let data = {};
      if (status == '1') {
        //  let data1 = await validate();
        //  data = {
        //   remarks:data1.remarks,
        //   dataMap:data1.dataMap
        //  }
        data = await validate();
      }
      if (status == '3') {
        // 拒收
        data = await validateReason();
      }
      setDrawerProps({ confirmLoading: true });
      const params: any = {
        // isNewRecord: record.value.isNewRecord,
        id: record.value.id,
      };
      data.status = status;
      data.id = record.value.id;
      // data.pmMaterialneedArrsList = await getPmMaterialneedArrsList();
      // console.log('submit', params, data, record);
      const res = await pmAsnShrecSaveByAsn(params, data);
      showMessage(res.message);
      setTimeout(closeDrawer);
      setTimeout(closeModal);
      emit('success', data);
    } catch (error: any) {
      if (error && error.errorFields) {
        showMessage(t('您填写的信息有误，请根据提示修正。'));
      }
      console.log('error', error);
    } finally {
      setDrawerProps({ confirmLoading: false });
    }
  }

  async function handSelect(selectData) {
    let arr = await pmMaterialneedArrsTable.getDataSource();
    selectData.forEach((item) => {
      let flag = true;
      arr.forEach((res) => {
        if (res.metercode == item.mcode) {
          flag = false;
        }
      });
      if (flag) {
        pmMaterialneedArrsTable.insertTableDataRecord({
          ...item,
          // id: new Date().getTime() + item.id,
          editable: true,
          isNewRecord: true,
          basInv: {
            mcode: item.mcode,
            mname: item.mname,
            mstd: item.mstd,
          },
          metercode: item.mcode,
          querycount: item.num,
          actualnum: item.num,
          sourceId: item.id,
          projectno: item.pcode,
        });
      }
    });
  }
</script>
<style lang="less" scoped>
  :deep(.jeesite-editable-cell__action) {
    display: none;
  }

  /* .jeesite-editable-cell__action {
    display: none;
  } */

  :deep(.edit-cell-align-center) {
    width: 100% !important;
  }
</style>
